package cn.gbase.jiangsu.data.transfer.action;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.nutz.dao.QueryResult;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.filter.CheckSession;

import cn.gbase.jiangsu.data.transfer.bean.Supplier;
import cn.gbase.jiangsu.data.transfer.bean.SupplierUser;
import cn.gbase.jiangsu.data.transfer.service.SupplierService;

@IocBean
@At("/supplier")
@Filters(@By(type = CheckSession.class, args = { "supplierUser", "jsp:/supplierIndex" }))
public class SupplierAction {

	@Inject
	private SupplierService supplierService;

	@Inject("java:$config.get('supplierUserAclStr')")
	private String supplierUserAclStr;

	/**
	 * 分页查询供货商（供货商管理页面）.
	 * 
	 * @param currentPage
	 * @param groupId
	 * @param addTime
	 * @param keyword
	 * @param req
	 */
	@At("/listSupplier")
	@Ok("jsp:/supplier/listSupplier")
	public QueryResult listSupplier(@Param("currentPage") int currentPage, @Param("keyword") String keyword,
			@Param("contact") String contact, HttpServletRequest request) {

		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("keyword", keyword);
		itemMap.put("contact", contact);
		request.setAttribute("formdata", itemMap);

		return supplierService.getSupplierList(currentPage, keyword, contact);
	}

	/**
	 * 跳转到添加供货商页面（供货商管理）.
	 */
	@At("/toAddSupplier")
	@Ok("jsp:/supplier/editSupplier")
	public void toAddSupplier(HttpServletRequest req) {

	}

	/**
	 * 跳转到修改供货商页面.
	 */
	@At("/toEditSupplier")
	@Ok("jsp:/supplier/editSupplier")
	public void toEditSupplier(@Param("id") int id, HttpServletRequest req) {

		// 要修改的供货商
		Supplier p = supplierService.getSupplier(id);
		req.setAttribute("formdata", p);
	}

	/**
	 * 保存供货商.
	 * 
	 * @param sp
	 */
	@At("/saveSupplier")
	@POST
	@Ok(">>:/supplier/listSupplier")
	@Fail("jsp:/supplier/editSupplier")
	@Aop("validationInterceptor")
	public void saveSupplier(@Param("..") Supplier Supplier) {
		supplierService.addOrUpdSupplier(Supplier);
	}

	/**
	 * 删除供货商（逻辑删除？）.
	 */
	@At("/delete")
	@Ok("json")
	public String delete(@Param("id") int id) {
		supplierService.deleteSupplier(id);
		return "{id:0}";
	}

	/**
	 * 删除供货商（逻辑删除？）.
	 */
	@At("/deleteMany")
	@Ok("json")
	public String deleteMany(@Param("idStr") String idStr) {
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			supplierService.deleteSupplier(Integer.valueOf(id));
		}
		return "{id:0}";
	}

	// -----------------------------下面是供应商的用户管理------------------------

	@At("/listUser")
	@Ok("jsp:/supplier/listUser")
	public QueryResult list(@Param("sid") int sid, @Param("p") int pageNumber, @Param("username") String username,
			@Param("realname") String realname, HttpServletRequest request) {

		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("username", username);
		itemMap.put("realname", realname);
		itemMap.put("sid", "" + sid);
		request.setAttribute("formdata", itemMap);

		// 查询数据
		return supplierService.getUserList(pageNumber, username, realname, sid);
	}

	@At("/addUser")
	@Ok("jsp:/supplier/editUser")
	public void toAddPage(@Param("sid") int sid, HttpServletRequest request, HttpSession session) {

		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("supplierId", "" + sid); // 供货商ID
		request.setAttribute("formdata", itemMap);

		// 权限名称，初始权限
		String[] aclNameArray = supplierUserAclStr.split(",");
		int[] aclArray = new int[aclNameArray.length];

		// 权限
		session.setAttribute("aclNameArray", aclNameArray);
		session.setAttribute("aclArray", aclArray);

	}

	@At("/addUser")
	@POST
	@Ok(">>:/supplier/listUser?p=1&sid=${obj.supplierId}")
	@Fail("jsp:/supplier/editUser")
	public SupplierUser add(@Param("..") SupplierUser user, HttpServletRequest request, HttpSession session) {
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("supplierId", "" + user.getSupplierId()); // 供货商ID
		request.setAttribute("formdata", itemMap);

		// 权限名称，初始权限
		String[] aclNameArray = supplierUserAclStr.split(",");
		int[] aclArray = new int[aclNameArray.length];

		// 权限
		session.setAttribute("aclNameArray", aclNameArray);
		session.setAttribute("aclArray", aclArray);
		if (!supplierService.addOrUpdUser(user)) {
			request.setAttribute("errmsg", "该用户名的用户已经存在。"); // 错误信息
			request.setAttribute("formdata", user); // 表单数据
			throw new RuntimeException();
		}
		return user;
	}

	@At("/editUser")
	@Ok("jsp:/supplier/editUser")
	public void toEditPage(@Param("id") int userId, HttpServletRequest request, HttpSession session) {

		// 取得用户数据，放入表单中
		SupplierUser user = supplierService.getUser(userId);
		request.setAttribute("formdata", user);

		// 权限名称，初始权限
		String[] aclNameArray = supplierUserAclStr.split(",");
		char[] aclArray = user.getAclStr().toCharArray();

		// 权限
		session.setAttribute("aclNameArray", aclNameArray);
		session.setAttribute("aclArray", aclArray);
	}

	/**
	 * 删除用户.
	 */
	@At("/deleteUser")
	@Ok("json")
	public String deleteUser(@Param("id") int id) {
		supplierService.deleteUser(id);
		return "{id:0}";
	}

	/**
	 * 删除多个用户.
	 */
	@At("/deleteManyUser")
	@Ok("json")
	public String deleteManyUser(@Param("idStr") String idStr) {
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			supplierService.deleteUser(Integer.valueOf(id));
		}
		return "{id:0}";
	}

}
